/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iqq.ui;

import iqq.util.ErrorMessage;
import iqq.util.BrowserUtil;
import iqq.util.Log;
import iqq.util.PersistenceUtils;
import iqq.util.FileLockUtil;
import atg.taglib.json.util.JSONException;
import atg.taglib.json.util.JSONObject;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import iqq.comm.ComboBoxRenderer;

/**
 *
 * @author chenzhihui
 */
public class LoginPanel extends javax.swing.JPanel {

    private MainFrame mainFrame = MainFrame.getMainFrame();
    private JSONObject memberList = null;

    /**
     * Creates new form LoginPanel
     */
    public LoginPanel() {

        ResourceBundle bundle = ResourceBundle.getBundle("iqq/res/res"); // NOI18N
        MainFrame.getMainFrame().setIBackground(bundle.getString("iqq.defLoginBg"));

        initComponents();
        this.setVisible(true);

        initLogin();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblLogo = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        RememberCheckBox = new javax.swing.JCheckBox();
        comboLoginStatus = new javax.swing.JComboBox();
        btnLogin = new javax.swing.JButton();
        combAccount = new javax.swing.JComboBox();
        textPassword = new javax.swing.JPasswordField();
        lblRegister = new javax.swing.JLabel();
        lblForgetPassword = new javax.swing.JLabel();
        lblAccountMenage = new javax.swing.JLabel();

        setOpaque(false);
        setPreferredSize(new java.awt.Dimension(255, 555));

        lblLogo.setFont(lblLogo.getFont());
        lblLogo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblLogo.setPreferredSize(new java.awt.Dimension(255, 100));

        jLabel1.setFont(new java.awt.Font("AR PL UMing CN", 0, 15)); // NOI18N
        jLabel1.setForeground(java.awt.Color.white);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("iqq/res/res"); // NOI18N
        jLabel1.setText(bundle.getString("iqq.acount")); // NOI18N

        jLabel2.setFont(new java.awt.Font("AR PL UMing CN", 0, 15)); // NOI18N
        jLabel2.setForeground(java.awt.Color.white);
        jLabel2.setText(bundle.getString("iqq.password")); // NOI18N

        RememberCheckBox.setFont(new java.awt.Font("AR PL UMing CN", 0, 15)); // NOI18N
        RememberCheckBox.setSelected(true);
        RememberCheckBox.setText(bundle.getString("iqq.res.rememberPassword")); // NOI18N

        comboLoginStatus.setFont(new java.awt.Font("AR PL UMing CN", 0, 15)); // NOI18N
        comboLoginStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "我在线上", "Q我吧", "忙碌", "隐身", "静音" }));

        btnLogin.setFont(new java.awt.Font("AR PL UMing CN", 0, 15)); // NOI18N
        btnLogin.setText(bundle.getString("iqq.login")); // NOI18N
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toLogin(evt);
            }
        });

        combAccount.setEditable(true);
        combAccount.setFont(new java.awt.Font("AR PL UMing CN", 0, 15)); // NOI18N
        combAccount.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                combAccountItemStateChanged(evt);
            }
        });

        textPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textPasswordActionPerformed(evt);
            }
        });
        textPassword.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                textPasswordFocusGained(evt);
            }
        });

        lblRegister.setFont(new java.awt.Font("AR PL UMing CN", 0, 12)); // NOI18N
        lblRegister.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iqq/res/images/icon/icon.png"))); // NOI18N
        lblRegister.setText("申请QQ帐号");
        lblRegister.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblRegisterMouseClicked(evt);
            }
        });

        lblForgetPassword.setFont(new java.awt.Font("AR PL UMing CN", 0, 12)); // NOI18N
        lblForgetPassword.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iqq/res/images/icon/account_find.png"))); // NOI18N
        lblForgetPassword.setText("找回QQ帐号");
        lblForgetPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                lblForgetPasswordKeyPressed(evt);
            }
        });

        lblAccountMenage.setFont(new java.awt.Font("AR PL UMing CN", 0, 12)); // NOI18N
        lblAccountMenage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iqq/res/images/icon/account_m.png"))); // NOI18N
        lblAccountMenage.setText("管理账号");
        lblAccountMenage.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblAccountMenageMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblLogo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblRegister)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblAccountMenage)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(comboLoginStatus, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(RememberCheckBox)
                                    .addComponent(combAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGap(33, 33, 33))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblForgetPassword)
                            .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(lblLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addComponent(jLabel1)
                .addGap(11, 11, 11)
                .addComponent(combAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(12, 12, 12)
                .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(RememberCheckBox)
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboLoginStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnLogin))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 146, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblRegister)
                    .addComponent(lblAccountMenage))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblForgetPassword)
                .addGap(21, 21, 21))
        );

        lblLogo.getAccessibleContext().setAccessibleName("logo");
    }// </editor-fold>//GEN-END:initComponents

    private void toLogin(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toLogin
        // TODO add your handling code here:
        String account = this.combAccount.getSelectedItem().toString();
        if(!FileLockUtil.getFileLock(account)) {
            ErrorMessage.show("QQ已经登录！ Account:" + account);
            return;
        }
        if (mainFrame.getMap() == null) {
            Map map = new HashMap();
            mainFrame.setMap(map);
        }

        Log.println("to login");
        Map loginMap = new HashMap();
        loginMap.put("account", account);
        loginMap.put("password", this.textPassword.getText().toString());
        loginMap.put("verifyCode", this.textPassword.getText().toString());
        loginMap.put("rememberPassword", this.RememberCheckBox.isSelected());
        int loginStatusIndex = this.comboLoginStatus.getSelectedIndex();
        String loginStatus = "online";
        switch (loginStatusIndex) {
            case 1: {
                loginStatus = "callme";
                break;
            }
            case 2: {
                loginStatus = "busy";
                break;
            }
            case 3: {
                loginStatus = "hidden";
                break;
            }
            case 4: {
                loginStatus = "silent";
                break;
            }
        }
        loginMap.put("loginStatus", loginStatus);

        LoginProcessPanel loginProcessPanel = new LoginProcessPanel();
        try {
            mainFrame.getMap().put("loginMap", loginMap);
            loginProcessPanel.login();
        } catch (Exception ex) {
            Logger.getLogger(LoginPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        mainFrame.getMap().put("loginPanel", this);
        mainFrame.setContentPane(loginProcessPanel);
        mainFrame.validate();

    }//GEN-LAST:event_toLogin

    private void textPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textPasswordActionPerformed
        // TODO add your handling code here:
        this.toLogin(evt);
    }//GEN-LAST:event_textPasswordActionPerformed

    private void combAccountItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_combAccountItemStateChanged
        // TODO add your handling code here:
        String account = this.combAccount.getSelectedItem().toString();
        try {
            if (memberList != null && !memberList.isNull(account)) {
                this.textPassword.setText(memberList.getString(account));
            }
        } catch (JSONException ex) {
            Logger.getLogger(LoginPanel.class.getName()).log(Level.SEVERE, null, ex);
        }


    }//GEN-LAST:event_combAccountItemStateChanged

    private void lblRegisterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblRegisterMouseClicked
         BrowserUtil.openURL("http://zc.qq.com/chs/index.html");
    }//GEN-LAST:event_lblRegisterMouseClicked

    private void lblForgetPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lblForgetPasswordKeyPressed
        // TODO add your handling code here:
        BrowserUtil.openURL("http://imsafe.qq.com/");
    }//GEN-LAST:event_lblForgetPasswordKeyPressed

    private void lblAccountMenageMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblAccountMenageMouseClicked
        // TODO add your handling code here:
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem deleteItem = new JMenuItem("删除账号");
        JMenuItem clearPasswordItem = new JMenuItem("清除密码");
        popupMenu.add(deleteItem);
        popupMenu.add(clearPasswordItem);
        Component c = (Component) evt.getSource();
        popupMenu.show(c, -1, c.getHeight());
        deleteItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String account = (String) combAccount.getSelectedItem();
                combAccount.removeItemAt(combAccount.getSelectedIndex());
                Map m = new HashMap();
                m.put("account", account);
                PersistenceUtils.getInstance().update(m);
            }
        });

        clearPasswordItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String account = (String) combAccount.getSelectedItem();
                combAccount.removeItemAt(combAccount.getSelectedIndex());
                Map m = new HashMap();
                m.put("account", account);
                m.put("password", "");
                PersistenceUtils.getInstance().update(m);
            }
        });
    }//GEN-LAST:event_lblAccountMenageMouseClicked

    private void textPasswordFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textPasswordFocusGained
        // TODO add your handling code here:
        String account = this.combAccount.getSelectedItem().toString();
        if (memberList != null && memberList.isNull(account)) {
            this.textPassword.setText("");
        }

    }//GEN-LAST:event_textPasswordFocusGained
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox RememberCheckBox;
    private javax.swing.JButton btnLogin;
    private javax.swing.JComboBox combAccount;
    private javax.swing.JComboBox comboLoginStatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblAccountMenage;
    private javax.swing.JLabel lblForgetPassword;
    private javax.swing.JLabel lblLogo;
    private javax.swing.JLabel lblRegister;
    private javax.swing.JPasswordField textPassword;
    // End of variables declaration//GEN-END:variables

    private void initLogin() {
        ComboBoxRenderer cbr = new ComboBoxRenderer();
        this.combAccount.setRenderer(cbr);

        memberList = PersistenceUtils.getInstance().loadMemberList();
        if (memberList != null) {
//            for (Object s : memberList.toHashMap().keySet()) {
//                this.combAccount.addItem(s);
//            }
            Set set = memberList.toHashMap().keySet();
            Object[] obj = set.toArray();
            Log.println(obj.length);
            for (int i = set.size() - 1; i > -1; i--) {
                this.combAccount.addItem(obj[i]);
            }
        }

    }
}
